<script setup>
import { reactive } from 'vue'

import { Swiper, SwiperSlide } from 'swiper/vue'
import { Pagination, Mousewheel, Keyboard } from 'swiper/modules'
import 'swiper/css'
import 'swiper/css/pagination'

import { ImageViewModel } from '@/utils/ValueFunction.js'
import { ImagePreview } from 'img-preview-v'

const props = defineProps({
  list: {
    // 数据源
    type: Array,
    default: () => [],
    required: true,
    validator: (value) => {
      // 进行自定义验证

      if (!Array.isArray(value)) {
        return false
      }
      return value.every((item) => {
        return (
          item instanceof ImageViewModel &&
          item != null &&
          typeof item.id === 'number' &&
          typeof item.url === 'string'
        )
      })
    }
  },
  lazyLoad: {
    // 是否懒加载
    default: true,
    type: Boolean
  }
})

const state = reactive({
  data: props.list, // 数据源
  showBigImg: false, // 是否显示大图
  bigImages: [] // 大图的数组
})

/**
 * 点击显示大图
 * @param {ImageViewModel} val 数据源
 */
function handleClickImg(val) {
  state.bigImages.length = 0
  state.bigImages.push(val?.url)
  state.showBigImg = true
}
function handleCloseBigImage() {
  state.showBigImg = false
}
</script>

<template>
  <swiper
    :spaceBetween="30"
    :centeredSlides="true"
    :pagination="{
      clickable: true
    }"
    :mousewheel="{
      enabled: true,
      forceToAxis: true
    }"
    :modules="[Pagination, Mousewheel, Keyboard]"
    class="imageSwiper"
  >
    <swiper-slide v-for="item in state.data" :key="item.id" :lazy="state.lazyLoad">
      <img :src="item.url" loading="lazy" class="c-img" @click="handleClickImg(item)" />
    </swiper-slide>
  </swiper>
  <ImagePreview
    v-if="state.showBigImg"
    :url-list="state.bigImages"
    :teleported="true"
    @close="handleCloseBigImage"
  ></ImagePreview>
</template>

<style scoped>
.imageSwiper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.imageSwiper .swiper-slide {
  text-align: center;
  font-size: 18px;
  background: #fff;

  display: flex;
  justify-content: center;
  align-items: center;
}
.c-img {
  width: 100%;
  max-height: 100%;
  object-fit: contain;
}
</style>
